package com.socialbank.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.fasterxml.jackson.databind.ObjectMapper;

public class BaseController {
	/**
	 * 登录认证异常
	 */
	@ExceptionHandler({ UnauthenticatedException.class,AuthenticationException.class })
	public String authenticationException(HttpServletRequest request, HttpServletResponse response) {
		if (com.socialbank.web.util.WebUtilsPro.isAjaxRequest(request)) {
			// 输出JSON
			Map<String, Object> map = new HashMap<>();
			map.put("code", "-999");
			map.put("message", "未登录");
			writeJson(map, response);
			return null;
		} else {
			return "redirect:/login";
		}
	}

	/**
	 * 权限异常
	 */
	@ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
	public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
		if (com.socialbank.web.util.WebUtilsPro.isAjaxRequest(request)) {
			// 输出JSON
			Map<String, Object> map = new HashMap<>();
			map.put("code", "-998");
			map.put("message", "无权限");
			writeJson(map, response);
			return null;
		} else {
			return "redirect:/refuse.jsp";
		}
	}

	/**
	 * 输出JSON
	 *
	 * @param response
	 * @author SHANHY
	 * @create 2017年4月4日
	 */
	private void writeJson(Map<String, Object> map, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			out = response.getWriter();
			ObjectMapper mapper = new ObjectMapper();
			out.write(mapper.writeValueAsString(map));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	
	public void print(HttpServletResponse response, String result) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("text/html;charset=UTF-8");			
			response.getWriter().print(result);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(response.getWriter()!=null){
					//System.out.println("Closing PrintWriter");
					response.getWriter().close();
				}
				else{
					System.out.println("PrintWriter not open");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
